<template>
	<view class="page has-fixed-footer">
		<page-header :launchFrom="launchFrom" :showPlaceHolder="false" :showTitle="false"></page-header>
		<!-- 内容 -->
		<view class="content">
			<view class="title">
				{{store.getters.userType == '2' ? '供应商认证':'供应链认证'}}
			</view>
			<view class="prompt">
				{{store.getters.userType == '2' ? '完善以下资料，通过供应商认证':'完善以下资料，通过供应链认证'}}
			</view>
			<fui-steps :items="items" lineBold :fontWeight="550" :isMark="false" :current="current" :size="24"
				direction="row" :isWait="true" :lineThrough="true" color="#999999" nodeColor="#999999"></fui-steps>
			<view class="ask">
				<view class="ask-title">
					拍摄证件要求
				</view>
				<view class="ask-content">
					拍摄时确保营业执照、身份证，<text>边框完整</text>，<text>字体清晰</text>，<text>亮度
						均匀</text>
				</view>
			</view>
			<fui-section descrColor="#666666" descrTop="30" title="上传营业执照" isLine color="#333333" lineWidth="4px"
				:marginTop="30" descr="拍摄并上传营业执照"></fui-section>
			<view style="padding: 20rpx;">
				<upload-image type="business" :defaultList="form.businessLicense ? [form.businessLicense] : []" @uploaded="uploadedBusiness"></upload-image>
			</view>
			<fui-section v-if="form.creditCode" descrColor="#666666" title="公司信息" isLine color="#333333" lineWidth="4px"
				:marginTop="30"></fui-section>
			<view class="fui-wrap" v-if="form.creditCode">
				<fui-form ref="formRef" :model="form" :top="store.getters.statusBarHeight">
					<fui-form-item label="公司名称" labelWeight="600" labelWidth="200" :left="0" labelSize="28"
						prop="companyName">
						<fui-input :borderBottom="false" color="#333333" size="28" :padding="[0]" placeholder="请输入公司名称"
							v-model="form.companyName"></fui-input>
					</fui-form-item>
					<fui-form-item label="社会信用代码" labelWeight="600" labelWidth="200" :left="0" labelSize="28"
						prop="creditCode">
						<fui-input :borderBottom="false" color="#333333" size="28" :padding="[0]"
							placeholder="请输入社会信用代码" v-model="form.creditCode"></fui-input>
					</fui-form-item>
					<fui-form-item label="公司地址" labelWeight="600" :left="0" labelWidth="200" labelSize="28"
						prop="address">
						<fui-input :borderBottom="false" color="#333333" size="28" :padding="[0]" placeholder="请输入公司地址"
							v-model="form.address"></fui-input>
					</fui-form-item>
					<template v-if="store.getters.userType === '2'">
						<fui-form-item label="运营范围" arrow arrowColor="#999999" prop="range" labelWeight="600" :left="0"
							labelWidth="200" labelSize="28" @click="onShowRangePicker">
							<fui-input :borderBottom="false" :padding="[0]" placeholder="请选择运营范围" v-model="form.rangeText"
								size="28" disabled></fui-input>
						</fui-form-item>
						<fui-form-item label="运营品类" arrow arrowColor="#999999" labelWeight="600" :left="0" labelWidth="200"
							labelSize="28" prop="category" @click="onShowCategoryPicker">
							<fui-input :borderBottom="false" :padding="[0]" placeholder="请选择运营品类"
								v-model="form.categoryText" size="28" disabled></fui-input>
						</fui-form-item>
					</template>
					<!-- <fui-form-item v-if="store.getters.userType !== '2'" :bottomBorder="false" label="认证周期"
						labelWeight="600" :left="0" labelWidth="200" class="textarea-box" labelSize="28">
						<view class="cycle-box">
							<view class="cycle" :class="{'cycle-active': checkedCycleIndex == index}"
								v-for="(item,index) in cycleList" :key="index" @click="handleChangeCycle(index, item.val)">
								<image v-if="checkedCycleIndex == index" class="cycleimg"
									src="../../static/images/cycleimg.png" mode=""></image>
								{{item.name}}
							</view>
						</view>
					</fui-form-item> -->
					<fui-form-item :bottomBorder="false" label="公司描述" labelWeight="600" :left="0" labelWidth="200"
						class="textarea-box" labelSize="28" prop="description">
						<fui-textarea maxlength="200" :isCounter="true" radius="16" borderColor="#DFDFDF"
							v-model="form.description" placeholder="请输入公司描述" textareaBorder
							:marginTop="16"></fui-textarea>
					</fui-form-item>
				</fui-form>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="ui-fixed-footer ui-fixed-footer__white">
			<fui-button :disabled="!form.creditCode" height="78rpx" :margin="['242rpx','0','0','0 ']"
				disabledBackground="#DFDFDF" disabledColor="#666666" background="var(--fui-color-primary)" bold
				@click="submit">下一步</fui-button>
		</view>

		<!-- 选择运营范围 -->
		<multilevel-picker ref="rangePickerRef" :data="rangeData" :cacheData="rangeCacheData" :defaultProps="rangeProps"
			@submit="submitRange"></multilevel-picker>

		<!-- 选择运营品类 -->
		<multilevel-picker ref="categoryPickerRef" :maxLevel="1" :data="categoryData" :cacheData="categoryCacheData"
			@submit="submitCategory" :defaultProps="categoryProps"></multilevel-picker>

		<!-- 提示窗口 -->
		<fui-toast ref="toastRef">
			<view class="fui-toast__custom">
				<view class="toast">
					<image src="../../static/images/error.png" mode=""></image>
				</view>
				<view class="fui-toast__txt">您上传的营业执照上的社会信用代码</view>
				<view class="fui-toast__txt">
					与邀约时填写的不一致！
				</view>
			</view>
		</fui-toast>
	</view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import pageHeader from '@/components/header'
import uploadImage from '@/components/upload/image'
import multilevelPicker from '@/components/multilevel'
import systemApi from '@/api/system'
import goodsApi from '@/api/goods'
import supplierApi from '@/api/supplier'

const tab = inject('$tab')
const modal = inject('$modal')
const store = useStore()

// 步骤条
const current = ref(0)
const items = ref([{
	title: '公司认证',
	text: '1'
}, {
	title: '法人认证',
	text: '2'
}, {
	title: '负责人认证',
	text: '3'
}])

// 表单
const form = ref({
	businessLicense: '',
	companyName: '',
	creditCode: '',
	corporationName: '',
	address: '',
	description: '',
	authenticationCycle: 1, // 认证周期
})
const formRef = ref(null)
const cycleList = ref([
	{ name: '一年', val: 1 },
	{ name: '两年', val: 2 }, 
	{ name: '三年', val: 3 }
])
const rules = computed(() => {
	let arr = [
		{
			name: 'companyName',
			rule: ['required'],
			msg: ['请输入公司名称']
		}, {
			name: 'creditCode',
			rule: ['required'],
			msg: ['请输入社会信用代码']
		}, {
			name: 'address',
			rule: ['required'],
			msg: ['请输入公司地址']
		}, {
			name: 'description',
			rule: ['required'],
			msg: ['请输入公司描述']
		}
	]
	if (store.getters.userType == '2') {
		arr = arr.concat([
			{
				name: 'rangeValue',
				rule: ['required'],
				msg: ['请选择运营范围']
			}, {
				name: 'categoryValue',
				rule: ['required'],
				msg: ['请选择运营品类']
			}
		])
	}
	return arr
})

const launchFrom = ref('')
onLoad((option) => {
	launchFrom.value = option ? option.launchFrom : ''

	if (store.getters.userType == '2') {
		if (store.getters.regionData.length) {
			rangeData.value = store.getters.regionData
		} else {
			getRangeList()
		}
		getCategoryTempList()
	}

	getCompanyDetail()
})

// 选择运营范围
const rangeData = ref([])
const rangePickerRef = ref(null)
const rangeProps = {
	text: 'name',
	value: 'id',
	children: 'children'
}
const rangeCacheData = ref([])
const getRangeList = () => {
	systemApi.administration().then((res) => {
		if (res.code == 0) {
			rangeData.value = res.data
		}
	})
}
const onShowRangePicker = () => {
	rangePickerRef.value.show()
}
const submitRange = (res) => {
	form.value.rangeValue = res.label
	form.value.rangeText = res.text
	rangeCacheData.value = res.cacheData
}

// 选择运营品类
const categoryData = ref([])
const categoryPickerRef = ref(null)
const categoryProps = {
	text: 'name',
	value: 'id',
	children: 'children'
}
const categoryCacheData = ref([])
const getCategoryTempList = () => {
	goodsApi.getCategoryTempList().then((res) => {
		let result = res.data.filter(item => item.level === 0);
		categoryData.value = result
	})
}
const onShowCategoryPicker = () => {
	categoryPickerRef.value.show()
}
const submitCategory = (res) => {
	form.value.categoryValue = res.label
	form.value.categoryText = res.text
	categoryCacheData.value = res.cacheData
}

// 选择认证周期
const checkedCycleIndex = ref(0)
const handleChangeCycle = ((index, val) => {
	checkedCycleIndex.value = index
	form.value.authenticationCycle = val
})

const inviteCode = ref('') // 邀约时信用代码

// 获取公司信息
const companyApiUrl = computed(() => {
	let apiUrl = ''
  if (store.getters.userType === '1') apiUrl = 'getSupplyDetail'
  if (store.getters.userType === '2') apiUrl = 'getSupplierDetail'
  return apiUrl
})
const getCompanyDetail = () => {
	supplierApi[companyApiUrl.value](store.getters.companyId).then((res) => {
		if (res.code == 0 && res.data && res.data.info) res.data = res.data.info
		inviteCode.value = res.data.creditCode
		Object.keys(form.value).forEach((key) => {
			form.value[key] = res.data[key]
		})

		if (store.getters.userType === '1') {
			form.value.companyName = res.data.name
			form.value.authenticationCycle = 1
		} else {
			const rangeArr = res.data.yunyfw ? res.data.yunyfw.split('|') : []
			let rangeTextArr = rangeArr.map(item => item.split(',')[0])
			let rangeValueArr = rangeArr.map(item => item.split(',')[1])
			form.value.rangeValue =rangeValueArr.join(',')
			form.value.rangeText = rangeTextArr.join(',')

			const categoryArr = res.data.yunypl ? res.data.yunypl.split('|') : []
			let categoryTextArr = categoryArr.map(item => item.split(',')[0])
			let categoryValueArr = categoryArr.map(item => item.split(',')[1])
			form.value.categoryValue =categoryValueArr.join(',')
			form.value.categoryText = categoryTextArr.join(',')
		}
	})
}

// 上传
const uploadedBusiness = async (e) => {
	if (e[0]) {
		try {
			modal.loading()
			const res = await systemApi.uploadbusinessLicense({
				imageUrl: e[0]
			})
			modal.closeLoading()
			if (res.code == 0) {
				let obj = JSON.parse(res.data)
				form.value.businessLicense = e[0]
				form.value.companyName = obj['单位名称']
				form.value.creditCode = obj['社会信用代码']
				form.value.address = obj['地址']
				form.value.corporationName = obj['法人']
			}
		} catch (err) {
			modal.closeLoading()
			modal.msgError('读取错误，请确认上传正确的营业执照照片！')
		}
	}
}

// 下一步
const toastRef = ref(null)
const submit = (async () => {
	if (!form.value.businessLicense) {
		modal.msgError('请上传营业执照照片！')
		return
	}

	const validRes = await formRef.value.validator(form.value, rules.value)
	if (validRes.isPassed) {
		if (store.getters.userType == '2') {
			if (form.value.creditCode != inviteCode.value) {
				let obj = {}
				toastRef.value.show(obj)
				return
			}
		}
		uni.setStorageSync('business', form.value)
		tab.navigateTo('/pages/authentication/LegalPerson')
	}
})
</script>

<style lang="scss" scoped>
.page {
	position: relative;
	min-height: 100%;
	padding-bottom: 100rpx;

	.content {
		margin: 36rpx;

		.title {
			font-size: 40rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			color: #333333;
		}

		.prompt {
			font-size: 24rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			color: #999999;
			margin-top: 20rpx;
		}

		::v-deep.fui-steps__wrap {
			margin: 60rpx auto;
		}

		::v-deep.fui-sections__wrap {
			padding: 0 !important;
		}

		:deep(.fui-form__msg-wrap) {
			z-index: 11000;
		}

		::v-deep.fui-form__wrap-inner {
			padding: 0 !important;
		}

		::v-deep.fui-input__self {
			font-weight: bold;
		}

		::v-deep.uni-input-placeholder {
			font-weight: 500;
		}

		::v-deep.fui-form__item-content {
			font-weight: bold;
		}

		::v-deep.uni-textarea-placeholder {
			font-weight: 500;
		}

		.ask {
			width: 100%;
			padding: 22rpx 20rpx 24rpx 28rpx;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			background-color: #FFF3E4;
			box-sizing: border-box;

			.ask-title {
				font-size: 28rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				color: #333333;
			}

			.ask-content {
				margin-top: 16rpx;
				font-size: 24rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #999999;

				text {
					color: #F95A5A;
				}
			}
		}

		::v-deep.textarea-box .fui-form__wrap-inner {
			display: initial !important;
		}

		.cycle-box {
			display: flex;
			align-items: center;
			margin-top: 20rpx;

			.cycle {
				width: 160rpx;
				height: 64rpx;
				background: #F5F7FE;
				border-radius: 0rpx 0rpx 0rpx 0rpx;
				opacity: 1;
				border: 2rpx solid #E7EBFB;
				font-size: 24rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #333333;
				text-align: center;
				line-height: 64rpx;
				margin-right: 20rpx;
				position: relative;
			}

			.cycle-active {
				font-weight: bold;
				color: var(--fui-color-primary);
				border: 2rpx solid var(--fui-color-primary);
			}

			.cycleimg {
				width: 30rpx;
				height: 27rpx;
				display: block;
				position: absolute;
				right: 0;
				bottom: 0;
			}
		}

	}

	.fui-toast__custom {
		width: 594rpx;
		height: 352rpx;
		padding: 42rpx 18rpx 0 18rpx;
		box-sizing: border-box;

		.toast {
			width: 128rpx;
			height: 128rpx;
			margin: 0 auto;
			background-color: #FFFFFF;
			border-radius: 50%;
			margin-bottom: 42rpx;

			image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}

		.fui-toast__txt {
			font-size: 32rpx;
			font-weight: 400;
			color: #FFFFFF;
			text-align: center;
			padding-bottom: 8rpx;
		}

	}
}
</style>